#!/bin/sh
# Generate LLVM IR from C source files in "test" directory
LLVM_DIR=/home/teacher/Glucose180/llvm-19.1.0	# Path to LLVM installation
#CLANG_FLAGS="-O0 -g3"

WORK_DIR=$(cd `dirname $0`; cd .; pwd)	# Directory of this script's parent
# If `WORK_DIR` contains "clr", set `LLVM_DIR` to "/usr"
if [[ $WORK_DIR == *"clr"* ]]; then
	LLVM_DIR="/usr"
fi
TEST_DIR="$WORK_DIR/test"			# Directory containing test C files
OUT_DIR=$TEST_DIR
LLVM_CLANG=$LLVM_DIR/bin/clang		# Path to clang compiler
LLVM_OPT=$LLVM_DIR/bin/opt		# Path to opt tool

# For all C files in the test directory
for c_file in `ls $TEST_DIR/*.c`; do
	base_name=$(basename $c_file .c)	# Get base name without extension
	ir_file="$OUT_DIR/${base_name}.ll"	# IR file path
	ir_m2r_file="$OUT_DIR/${base_name}-m2r.ll"	# IR file path

	echo -e "\033[;36mInfo:\033[0m Generating LLVM IR for $c_file"
	# Compile C file to LLVM bitcode
	$LLVM_CLANG -Xclang -disable-O0-optnone -O0 -emit-llvm -S $c_file -o $ir_file
	# Run "mem2reg" pass
	$LLVM_OPT -S -passes=mem2reg $ir_file -o $ir_m2r_file
	# Run "dot-callgraph" pass
	$LLVM_OPT -passes=dot-callgraph $ir_m2r_file &> /dev/null
	# Callgraph dot file name
	dot_file="$ir_m2r_file.callgraph.dot"
	# Check if dot file is generated
	if [ -f $dot_file ]; then
		echo -e "\033[;36mInfo:\033[0m Callgraph dot file generated"
	else
		echo -e "\033[;35mWarning:\033[0m Failed to get callgraph dot file"
	fi
	# And the png file name
	png_file="$OUT_DIR/${base_name}-cg.png"
	dot -Tpng $dot_file -o $png_file

	# Optionally, you can run optimization passes here
	# $LLVM_OPT -O2 $bc_file -o $bc_file
done
